package com.yang.service.Impl;

import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.yang.exception.BusinessException;
import com.yang.mapper.SysUserMapper;
import com.yang.mapper.SysUserRoleMapper;
import com.yang.pojo.SysUser;
import com.yang.pojo.SysUserRole;
import com.yang.qrCode.QRCodeUtil;
import com.yang.service.SysUserService;
import com.yang.utils.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by 杨天可 on 2022/3/29 11:08
 */

@Service("sysUserService")
@Transactional
public class SysUserServiceImpl implements SysUserService {
    @Resource
    SysUserMapper sysUserMapper;
    @Resource
    SysUserRoleMapper sysUserRoleMapper;
    @Resource
    RedisTemplate<String, Integer> redisTemplate;
    @Resource
    private FastFileStorageClient storageClient ;

    @Override
    public SysUser findByPhone(String phone) {
        return sysUserMapper.findByPhone(phone);
    }

    @Override
    public Map<String, Object> regist(SysUser sysUser) {
        JsonResult jsonResult = new JsonResult();
        SysUser byPhone = sysUserMapper.findByPhone(sysUser.getPhone());
        if (byPhone != null ) {
            throw new BusinessException("电话已被注册");
        }
        SysUser byEmail = sysUserMapper.findByEmail(sysUser.getEmail());
        if (byEmail != null ) {
            throw new BusinessException("邮箱已被注册");
        }
        SysUser sysUser1 = new SysUser();
        String salt = CommonUtil.createSalt();
        sysUser1.setUsername(sysUser.getUsername());
        sysUser1.setEmail(sysUser.getEmail());
        sysUser1.setPhone(sysUser.getPhone());
        sysUser1.setPassword(MD5.encodePassword(sysUser.getPassword(), salt));
        sysUser1.setShopName(sysUser.getShopName());
        sysUser1.setSalt(salt);
        int insert = sysUserMapper.insertSelective(sysUser1);
        if (insert > 0) {
            SysUser newUser = sysUserMapper.findByPhone(sysUser.getPhone());
            SysUserRole sysUserRole = new SysUserRole(newUser.getId(), Constants.ROLE_ID);
            sysUserRoleMapper.insert(sysUserRole);
            jsonResult.setCode(Constants.SUCCESS);
            jsonResult.setMsg("注册成功");
        } else {
            jsonResult.setCode(Constants.FAIL);
            jsonResult.setMsg("注册失败");
        }
        return jsonResult.getValues();
    }

    @Override
    public Map<String, Object> checkCode(String phone, Integer code) {
        JsonResult jsonResult = new JsonResult();
        SysUser byUsername1 = sysUserMapper.findByPhone(phone);
        if (byUsername1 != null) {
            /* 校验验证码*/
            Integer integer = redisTemplate.opsForValue().get(byUsername1.getEmail());
            if (integer == null || !integer.equals(code)) {
                throw new BusinessException("验证码错误");
            }
            jsonResult.setCode("200");
        }else{
            throw new BusinessException("用户不存在");
        }
        return jsonResult.getValues();
    }

    @Override
    public Map<String, Object> ChangePassword(String phone, String password) {
        JsonResult jsonResult = new JsonResult();
        SysUser byUsername = sysUserMapper.findByPhone(phone);
        /* 修改密码*/
        byUsername.setPassword(MD5.encodePassword(password, byUsername.getSalt()));
        int insert = sysUserMapper.updateByPrimaryKey(byUsername);
        if (insert > 0) {
            jsonResult.setCode("200");
            jsonResult.setMsg("修改成功");
        } else {
            jsonResult.setCode("500");
            jsonResult.setMsg("修改失败");
        }
        return jsonResult.getValues();
    }

    @Override
    public Map<String, Object> updateSysUser(SysUser sysUser) {
        JsonResult jsonResult = new JsonResult();
        try {
            if (sysUser.getId() == null) {
                throw new BusinessException("获取个人信息失败");
            }
            int result = sysUserMapper.updateById(sysUser);
            if (result > 0) {
                jsonResult.setCode("200");
                jsonResult.setMsg("修改成功");
            } else {
                jsonResult.setCode("400");
                jsonResult.setMsg("修改失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("系统开小差");
        }
        return jsonResult.getValues();
    }

    @Override
    public SysUser getSubject() {
        SysUser sysUser = new SysUser();
        try {
            Subject subject = SecurityUtils.getSubject();
            SysUser user = (SysUser) subject.getPrincipal();
            if (user != null) {
                sysUser = user;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("系统开小差");
        }
        return sysUser;
    }

    @Override
    public Map<String, Object> setQRCode(Integer userId) {

        JsonResult jsonResult = new JsonResult();
        SysUser sysUser = sysUserMapper.findById(userId);

        // 存放在二维码中的内容
        String text = "http://106.14.39.205:8084/#/orderIndex?userId="+userId;
        // 生成的二维码名称
        String  QRName = UUID.randomUUID().toString().replace("-","");


        //生成二维码
        try {
            InputStream encode = QRCodeUtil.encode(text, true);
            StorePath storePath = this.storageClient.uploadImageAndCrtThumbImage(
                    encode,encode.available(),"JPG", null);
            sysUser.setQrUrl(storePath.getFullPath());
            sysUserMapper.updateByPrimaryKey(sysUser);
            jsonResult.setCode(Constants.SUCCESS);
            jsonResult.setData(storePath.getFullPath());
            jsonResult.setMsg("生成成功，请点击保存，否则二维码会失效");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonResult.getValues();
    }

    @Override
    public SysUser getUserById(Integer userId) {
        return sysUserMapper.findById(userId);
    }

    @Override
    public Map<String,Object> getUserList(String userName, String phone, String startTime,String endTime,Integer pageSize,Integer currentPage) {
        JsonResult jsonResult = new JsonResult();
        if (StringUtils.isEmpty(startTime)){
            startTime = "2022-01-01";
        }
        if (StringUtils.isEmpty(endTime)){
            endTime = "2100-01-01";
        }
        Integer startPage = (currentPage-1)*pageSize;
        List<SysUser> userListLimit = sysUserMapper.getUserListLimit(userName, phone, startTime, endTime,startPage,currentPage);
        List<SysUser> userList = sysUserMapper.getUserListTotal(userName, phone, startTime, endTime);
        jsonResult.setMsg("获取成功");
        jsonResult.setCode(Constants.SUCCESS);
        jsonResult.setData(userListLimit);
        jsonResult.put("total",userList.size());
        return jsonResult.getValues();
    }

    @Override
    public Map<String, Object> deleteSysUser(Integer userId) {
        JsonResult jsonResult = new JsonResult();
        int i = sysUserMapper.deleteSysUser(userId);
        if (i > 0){
            jsonResult.setCode(Constants.SUCCESS);
            jsonResult.setMsg("删除成功");
        }else {
            jsonResult.setCode(Constants.ERROR);
            jsonResult.setMsg("删除失败");
        }
        return jsonResult.getValues();
    }

    @Override
    public List<SysUser> findAll() {
        return sysUserMapper.selectAll();
    }

}
